<?php
namespace app\common\service;


use app\common\helper\ImageHelper;
use app\common\util\Upload;
use app\common\util\Util;

class CounselorCardService extends BaseService
{


    /**
     * 后台: 添加顾问名片模版配置
     * @param $sid
     * @param $bg
     * @param $thumb
     * @param $card_config
     * @return array
     */
    public function addCounselorCardConfig($sid, $bg, $thumb, $card_config)
    {
        $data = [
            'sid' => $sid,
            'card_config' => $card_config ? json_encode($card_config, JSON_UNESCAPED_UNICODE) : '',
            'bg' => $bg,
            'thumb' => $thumb,
            'add_time' => time(),
            'is_template' => $this->isTemplateStore($sid) ? 1 : 0
        ];
        /*if ($this->isTemplateStore($sid)) {
            $data['is_template'] = 1;

            $id = db('counselor_card_config')->insertGetId($data);
            if (!$id) {
                return ['status' => 0, 'msg' => '添加失败，请联系管理员'];
            }

            $store_ids = db('store')->where('status', 1)->column('store_id');
            if (!$store_ids) {
                return ['status' => 1, 'msg' => '添加成功！'];
            }

            $batch_data = [];
            $data['org_id'] = $id;
            $data['status'] = 0;
            foreach ($store_ids as $k => $v) {
                if(!$this->isTemplateStore($v)){
                    $data['sid'] = $v;
                    $batch_data[$k] = $data;
                }
            }

            // 模版店铺批量插入其他店铺的数据
            $r = db('counselor_card_config')->insertAll($batch_data);
        } else {
            $data['is_template'] = 0;
            $r = db('counselor_card_config')->insert($data);
        }*/

        $r = db('counselor_card_config')->insert($data);

        return $r ? ['status' => 1, 'msg' => '添加成功'] : ['status' => 0, 'msg' => '添加失败'];
    }


    /**
     * 后台: 编辑顾问名片模版
     * @param $sid
     * @param $id
     * @param $bg
     * @param $thumb
     * @param $card_config
     * @return int|string
     * @throws \think\Exception
     */
    public function editCounselorCardConfig($sid, $id, $bg, $thumb, $card_config)
    {
        $data = [
            'card_config' => $card_config ? json_encode($card_config, JSON_UNESCAPED_UNICODE) : '',
            'bg' => $bg,
            'thumb' => $thumb,
            'update_time' => time()
        ];
        $r = db('counselor_card_config')->where(['sid' => $sid, 'id' => $id])->update($data);

        // 查询名片生成表中时候已生成过，若存在，则更新时间
        $build = db('counselor_card_build')->where(['sid' => $sid, 'config_id' => $id])->select();
        if($build){
            $r = db('counselor_card_build')->where(['sid' => $sid, 'config_id' => $id])->setField('config_update_time', time());
        }

        return $r !== false ? ['status' => 1, 'msg' => '编辑成功'] : ['status' => 0, 'msg' => '编辑失败'];
    }


    /**
     * 后台: 获取顾问名片模版详情
     * @param $sid
     * @param $id
     * @return array
     */
    public function getCounselorCardConfigDetail($sid, $id)
    {
        $info = db('counselor_card_config')
            ->field('id,card_config,bg,thumb,status')
            ->where(['sid' => $sid, 'id' => $id, 'status' => ['<>', -1]])
            ->find();
        if (!$info) {
            return ['status' => 0, 'msg' => '未找到相应模版'];
        }

        $info['card_config'] = $info['card_config'] ? json_decode($info['card_config']) : '';
        return ['status' => 1, 'msg' => '获取成功', 'data' => $info];
    }


    /**
     * 后台: 获取顾问名片模版列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getCounselorCardConfigList($sid, $p, $pageSize)
    {
        $where = ['sid' => $sid, 'status' => ['<>', -1]];
        $list = db('counselor_card_config')
            ->field('id,card_config,bg,thumb,status')
            ->where($where)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->order('add_time DESC')
            ->select();
        if ($list) {
            foreach ($list as $k => $v) {
                $list[$k]['card_config'] = $v['card_config'] ? json_decode($v['card_config']) : '';
            }
        }

        $count = db('counselor_card_config')->where($where)->count();

        $data = [
            'page' => ['count' => $count],
            'content' => $list
        ];
        return ['data' => $data, 'status' => 1, 'msg' => '获取成功'];
    }


    /**
     * 后台: 更改顾问名片模版状态
     * @param $sid
     * @param $id
     * @param $status
     * @return array
     * @throws \think\Exception
     */
    public function changeCounselorCardConfigStatus($sid, $id, $status)
    {
        $where = [
            'id' => $id,
            'sid' => $sid,
            'status' => ['<>', -1]
        ];
        $r = db('counselor_card_config')
            ->where($where)
            ->update(['status' => $status, 'update_time' => time()]);
        return $r ? ['status' => 1, 'msg' => '操作成功'] : ['status' => 0, 'msg' => '操作失败'];
    }


    /**
     * 后台: 获取模版店铺顾问名片列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return array
     */
    public function getTplStoreConfigList($sid, $p, $pageSize)
    {
        // 获取自身店铺已引用名片列表
        $where = [
            'sid' => $sid,
            'org_id' => ['>', 0],
            'status' => ['<>', -1]
        ];
        $org_ids = db('counselor_card_config')->where($where)->column('org_id');

        $tpl_where = [
            'sid' => config('template_sid'),
            'id' => ['not in', $org_ids],
            'status' => 1
        ];
        $list = db('counselor_card_config')
            ->field('id,card_config,bg,thumb,status')
            ->where($tpl_where)
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->order('add_time DESC')
            ->select();
        $count = db('counselor_card_config')->where($tpl_where)->count();

        $data = [
            'page' => ['count' => $count],
            'content' => $list
        ];
        return ['data' => $data, 'status' => 1, 'msg' => '获取成功'];
    }


    /**
     * 后台: 引用模版店铺顾问名片
     * @param $sid
     * @param $id
     * @return array
     */
    public function quoteTplStoreConfig($sid, $id)
    {
        // 获取模版详情
        $tpl_where = [
            'sid' => config('template_sid'),
            'id' => $id,
            'status' => ['<>', -1]
        ];
        $tpl_info = db('counselor_card_config')->where($tpl_where)->find();
        if (!$tpl_info) {
            return ['status' => 0, 'msg' => '该模版不存在'];
        }

        // 判断是否已经引入
        $where = [
            'sid' => $sid,
            'org_id' => $id,
            'status' => ['<>', -1]
        ];
        $info = db('counselor_card_config')->where($where)->find();
        if ($info) {
            return ['status' => 0, 'msg' => '您已经引入过啦'];
        }

        $data = [
            'sid' => $sid,
            'card_config' => $tpl_info['card_config'],
            'bg' => $tpl_info['bg'],
            'thumb' => $tpl_info['thumb'],
            'add_time' => time(),
            'is_template' => 0,
            'org_id' => $id,
            'status' => 0
        ];

        $r = db('counselor_card_config')->insert($data);

        return $r ? ['status' => 1, 'msg' => '引入成功'] : ['status' => 0, 'msg' => '引入失败'];
    }


    /**
     * 微信端: 顾问获取名片列表
     * @param $sid
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCounselorCardListFront($sid, $uid, $p, $pageSize)
    {
        $list = db('counselor_card_config')
            ->field('id,thumb')
            ->where(['sid' => $sid, 'status' => 1])
            ->order('add_time DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();

        foreach($list as $k => $v){
            $status = db('counselor_card_build')
                ->where([
                    'sid' => $sid,
                    'config_id' => $v['id'],
                    'counselor_uid' => $uid,
                    'status' => ['in', [0,1]]
                ])
                ->value('status');
            $list[$k]['status'] = $status ?? 0;
        }

        return $list;
    }


    /**
     * 微信端: 获取顾问名片
     * @param $sid
     * @param $counselor_uid
     * @param $config_id
     * @return array
     * @throws \think\Exception
     */
    public function getCounselorCard($sid, $counselor_uid, $config_id)
    {
        $info = db('counselor_card_config')->where(['sid' => $sid, 'id' => $config_id, 'status' => 1])->find();
        if (!$info) {
            return ['status' => 0, 'msg' => '当前模版不存在或已关闭'];
        }

        // 查询是否已生成
        $build_info = db('counselor_card_build')->where(['sid' => $sid, 'counselor_uid' => $counselor_uid, 'config_id' => $config_id])->find();
        if ($build_info && $build_info['config_update_time'] <= $build_info['update_time']){
            return [
                'data' => [
                    'id' => $build_info['id'],
                    'card_url' => $build_info['card_url'],
                    'status' => $build_info['status']
                ],
                'status' => 1,
                'msg' => '获取成功'
            ];
        }

        $counselor_info = db('user u')
                        ->field('u.user_id,u.user_name,u.user_mobile,u.user_headimgurl,cr.name as counselor_rank_name,s.phone,s.name as student_name')
                        ->join('user_integral ui', 'ui.userid=u.user_id')
                        ->join('students s', 's.uid=u.user_id', 'LEFT')
                        ->join('counselor_rank cr', 'ui.counselor_rank_id=cr.counselor_rank_id', 'LEFT')
                        ->where([
                            'u.user_id' => $counselor_uid,
                            'ui.counselor_status' => 1
                        ])
                        ->find();
        if(!$counselor_info){
            return ['status' => 0, 'msg' => '无上级顾问'];
        }

        if(!$counselor_info['user_name'] && $counselor_info['student_name']){
            $counselor_info['user_name'] = $counselor_info['student_name'];
        }

        if(!$counselor_info['user_mobile'] && $counselor_info['phone']){
            $counselor_info['user_mobile'] = $counselor_info['phone'];
        }

        // 顾问姓名电话必须存在
        if(!$counselor_info['user_name'] && !$counselor_info['user_mobile']){
            return ['status' => 0, 'msg' => '顾问姓名和电话不能为空'];
        }

        // 名片制作
        $img_url = $this->buildCounselorCard($sid, $counselor_info, json_decode($info['card_config'], 1), $info['bg']);

        //将图片上传到七牛云
        $_FILES[0] = [
            'name' => 'a.jpg',
            'type' => 'image/jpeg',
            'tmp_name' => $img_url,
            'size' => filesize($img_url)
        ];

        $qiniu = Upload::uploadFile();
        if($qiniu == false){
            return ['status'=> 0, 'msg'=>'生成名片上传图片时失败'];
        }

        $qiniu_img_url = Util::qiniu_url($qiniu);

        if($build_info){
            // 更新
            $r = db('counselor_card_build')->where('id', $build_info['id'])->update(['card_url' => $qiniu_img_url, 'update_time' => time()]);
            $build_id = $build_info['id'];
        } else {
            // 插入
            $build_data = [
                'sid' => $sid,
                'counselor_uid' => $counselor_uid,
                'config_id' => $config_id,
                'card_url' => $qiniu_img_url,
                'add_time' => time(),
                'config_update_time' => $build_info['update_time'] ?? 0,
                'update_time' => $build_info['update_time'] ?? 0
            ];
            $r = db('counselor_card_build')->insertGetId($build_data);
            $build_id = $r;
        }

        return $r ? ['data' => ['id' => $build_id, 'card_url' => $qiniu_img_url, 'status' => 0], 'status' => 1, 'msg' => '获取成功'] : ['status' => 0, 'msg' => '获取失败'];
    }


    /**
     * 创建顾问名片
     * @param $sid
     * @param array $counselor_info
     * @param array $card_config
     * @param $bg
     * @return string
     */
    public function buildCounselorCard($sid, $counselor_info = [], $card_config = [], $bg)
    {
//        $card_config = [
//            // 顾问姓名
//            [
//                'type' => 'name',
//                'dx' => '300',
//                'dy' => '300',
//                'color' => '255,0,0',
//                'size' => '18'
//            ],
//
//            // 顾问头像
//            [
//                'type' => 'avatar',
//                'dx' => '100',
//                'dy' => '100',
//            ],
//
//            // 顾问电话
//            [
//                'type' => 'phone',
//                'dx' => '300',
//                'dy' => '450',
//                'color' => '255,255,255',
//                'size' => '20'
//            ],
//
//            // 顾问二维码
//            [
//                'type' => 'qrcode',
//                'dx' => '500',
//                'dy' => '500'
//            ],
//
//            // 自定义文本
//            [
//                'type' => 'text',
//                'dx' => '300',
//                'dy' => '400',
//                'color' => '125,125,125',
//                'value' => 'haha',
//                'size' => '16'
//            ]
//        ];
//        $bg = 'http://or5rqhyqy.bkt.clouddn.com/a71503ee150352ba0aa344b06ff8666f17ade9751509601375';

        $counselor_card_path = './uploads/counselor_card/' . $counselor_info['user_id'] . DS;

        if(!file_exists($counselor_card_path)){
            mkdir($counselor_card_path, 0777, true);
        }

        foreach($card_config as $k => $v){
            // 顾问姓名
            if($v['type'] == 'name'){
                $bg = ImageHelper::mergeText($bg, $counselor_info['user_name'], $v['size'], $v['color'], $v['dx'], $v['dy'], $counselor_card_path);
            }

            // 顾问电话
            if($v['type'] == 'phone'){
                $bg = ImageHelper::mergeText($bg, $counselor_info['user_mobile'], $v['size'], $v['color'], $v['dx'], $v['dy'], $counselor_card_path);
            }

            // 顾问等级
            if($v['type'] == 'counselor_rank'){
                $bg = ImageHelper::mergeText($bg, $counselor_info['counselor_rank_name'], $v['size'], $v['color'], $v['dx'], $v['dy'], $counselor_card_path);
            }

            // 自定义文本
            if($v['type'] == 'text'){
                $bg = ImageHelper::mergeText($bg, $v['value'], $v['size'], $v['color'], $v['dx'], $v['dy'], $counselor_card_path);
            }

            // 头像
            if($v['type'] == 'avatar'){
                // 下载远程头像至本地
                $avatar = $counselor_card_path .'avatar_local.jpg';
                if(!file_exists($avatar)){
                    file_put_contents($avatar, Util::curl_get($counselor_info['user_headimgurl']));
                }

                // 压缩图片
                $avatar_zip = ImageHelper::resizeImg($avatar, 170, $counselor_card_path);
                // 裁减成圆角图片
                $avatar_src = ImageHelper::cutCorner($avatar_zip, 170, 170, $counselor_card_path);
                // 合并图片
                $bg = ImageHelper::mergeImg($bg, $avatar_src, $v['dx'], $v['dy'], $counselor_card_path);
            }

            // 二维码
            if($v['type'] == 'qrcode'){
                // 获取顾问带参二维码
                $wxService = new WeixinService();
                $qr_code = $wxService->get_user_qrcode($sid, $counselor_info['user_id']);

                $qrcode_url = $qr_code['data']->qrcode_url;

                // 保存至本地
                $qrcode = $counselor_card_path .'qrcode_local.jpg';
                if(!file_exists($qrcode)){
                    file_put_contents($qrcode, Util::curl_get($qrcode_url));
                }
                // 压缩
                $qrcode_zip = ImageHelper::resizeImg($qrcode, 240, $counselor_card_path);
                // 合并
                $bg = ImageHelper::mergeImg($bg, $qrcode_zip, $v['dx'], $v['dy'] ,$counselor_card_path);
            }
        }
        return $bg;
    }


    /**
     * 微信端: 顾问设置默认顾问名片
     * @param $sid
     * @param $counselor_uid
     * @param $build_id
     * @return array
     */
    public function setDefaultCounselorCard($sid, $counselor_uid, $build_id)
    {
        db('counselor_card_build')->where(['sid' => $sid, 'counselor_uid' => $counselor_uid, 'id' => ['<>', $build_id]])->setField('status', 0);
        $r = db('counselor_card_build')->where(['sid' => $sid, 'counselor_uid' => $counselor_uid, 'id' => $build_id])->setField('status', 1);
        return $r !== false ? ['status' => 1, 'msg' => '设置成功'] : ['status' => 0, 'msg' => '设置失败'];
    }


    /**
     * 微信端: 用户获取顾问名片
     * @param $sid
     * @param $uid
     * @return array
     */
    public function getCounselorCardByUser($sid, $uid)
    {
        $user_info = db('user_integral')->where(['sid' => $sid, 'userid' => $uid])->find();
        $counselor_uid = db('user_integral')
                        ->where([
                            'sid' => $sid,
                            'userid' => $user_info['counselor_id'],
                            'counselor_status' => 1
                        ])
                        ->value('userid');
        if(!$counselor_uid){
            $counselor_uid = db('user_integral')->where(['sid' => $sid, 'is_administrator' => 1])->value('userid');
            if(!$counselor_uid){
                return ['status' => 0, 'msg' => '不存在顾问信息'];
            }
        }

        $build_info = db('counselor_card_build cb')
                    ->field('cb.*')
                    ->join('counselor_card_config cc', 'cb.config_id=cc.id')
                    ->where([
                        'cb.sid' => $sid,
                        'cb.counselor_uid' => $counselor_uid,
                        'cb.status' => 1,
                        'cc.status' => 1
                    ])
                    ->find();
        if($build_info){
            return $this->getCounselorCard($sid, $counselor_uid, $build_info['config_id']);
        } else {
            $card_config = db('counselor_card_config')->where(['sid' => $sid, 'status' => 1])->order('id ASC')->find();
            if(!$card_config){
                return ['status' => 0, 'msg' => '未设置名片模版，无法生成名片'];
            }
            return $this->getCounselorCard($sid, $counselor_uid, $card_config['id']);
        }
    }

}